<template>
  <h1>Spu管理</h1>
  <el-button type="default"
             v-if="authority.spuInfoAdd"
             @click="add()">添加Spu</el-button>

  <el-table :data="pageInfo.list"
            stripe
            style="width:100%"
            border
            :header-cell-style="{textAlign:'center'}"
            :cell-style="{textAlign:'center'}">
    <el-table-column prop="spuName"
                     label="商品名称"></el-table-column>
    <el-table-column prop="spuDescription"
                     label="品牌描述"
                     :show-overflow-tooltip="true" width="350px">
    </el-table-column>
    <el-table-column prop="categoryName"
                     label="所属分类">
    </el-table-column>
    <el-table-column prop="brandName"
                     label="所属品牌">
    </el-table-column>
    <el-table-column prop="weight"
                     label="重量">
    </el-table-column>
    <el-table-column prop="publishStatus"
                     label="上架状态">
      <template #default="scope">
        <el-tag class="ml-2"
                v-if="scope.row.publishStatus == 1"
                effect="dark">上架</el-tag>
        <el-tag class="ml-2"
                effect="dark"
                v-if="scope.row.publishStatus == 0"
                type="danger">下架</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作"
                     width="530px">
      <template #default="scope">
        <el-button color="#00B2EE" style="color:azure" size="small" @click="toDetail(scope)">
          详细信息
        </el-button>
        <el-button color="#f36c21" @click="toAttr(scope)" style="color:azure" size="small">
          属性管理
        </el-button>
        <el-button color="#626aef" size="small" @click="toImageManage(scope)">
          图片管理
        </el-button>
        <el-button size="small"
                   type="primary"
                   @click="toSkuInfo(scope)">Sku管理</el-button>
        <el-button size="small"
                   type="success"
                   v-if="authority.spuInfoUpdate && scope.row.publishStatus === 0"
                   @click="publish(scope)">上架</el-button>
        <el-button size="small"
                   type="warning"
                   v-if="authority.spuInfoUpdate && scope.row.publishStatus === 1"
                   @click="publish(scope)">下架</el-button>
        <el-button size="small"
                   type="warning"
                   v-if="authority.spuInfoUpdate"
                   @click="edit(scope)">编辑</el-button>
        <el-button size="small"
                   type="danger"
                   v-if="authority.spuInfoDelete"
                   @click="del(scope)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination class="el-pagination"
                 layout="prev,pager,next,total,jumper,sizes"
                 :total="pageInfo.total"
                 v-model:current-page="pageInfo.pageNum"
                 v-model:page-size="pageInfo.pageSize"
                 :page-sizes="[3,5,10,20]"
                 background
                 @current-change="handleCurrentChange"
                 @size-change="handleSizeChange">
  </el-pagination>

  <el-drawer v-model="drawer_spu" title="title—useless" :with-header="false" size="35%">
      <span><h4>Spu详情信息</h4></span>
      <el-divider></el-divider>
      <span>
          <el-descriptions
              class="margin-top"
              :column="3"
              :size="small"
              :style="blockMargin"
              border
          >
              <el-descriptions-item label="品牌类别名称">{{SpuInfo.value.brandName}}{{SpuInfo.value.categoryName}}</el-descriptions-item>
              <el-descriptions-item label="商品名称">{{SpuInfo.value.spuName}}</el-descriptions-item>
              <el-descriptions-item label="上架信息" v-if="SpuInfo.value.publishStatus == 1">已上架</el-descriptions-item>
              <el-descriptions-item label="上架信息" v-if="SpuInfo.value.publishStatus == 0">已下架</el-descriptions-item>
              <el-descriptions-item label="商品描述" span="2">{{SpuInfo.value.spuDescription}}</el-descriptions-item>
              <el-descriptions-item label="商品重量">{{SpuInfo.value.weight}}</el-descriptions-item>
          </el-descriptions>
      </span>
  </el-drawer>

  <el-dialog v-model="disableDialog"
             title="编辑商品信息"
             center
             width="600px">
    <el-form :model="spuInfo"
             :rules="rules"
             ref="editSpuInfo"
             label-width="80px">
      <el-form-item label="商品名称"
                    prop="spuName">
        <el-input placeholder="请输入商品名称"
                  v-model="spuInfo.spuName"></el-input>
      </el-form-item>
      <el-form-item label="商品描述"
                    prop="spuDescription">
        <el-input autosize
                  type="textarea"
                  placeholder="请添加商品描述"
                  v-model="spuInfo.spuDescription"></el-input>
      </el-form-item>
      <el-form-item label="商品类别">
        <el-cascader
          placeholder="请选择商品类别"
          v-model="spuInfo.categoryId"
          :options="categories"
          :show-all-levels="false"
          :props="props"
          clearable
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item label="商品品牌">
        <el-select v-model="spuInfo.brandId" clearable placeholder="请选择商品品牌">
          <el-option
            v-for="item in brands"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品重量"
                    prop="weight">
        <el-input-number placeholder="请输入商品重量(单位:克)" v-model="spuInfo.weight" :precision="2" :step="0.1" :max="10000" /><span>&emsp;(tips:最大重量不超过10Kg)</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancelSave('editSpuInfo')">取消</el-button>
      <el-button type="primary"
                 @click="saveData('editSpuInfo')">保存</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="addDisableDialog"
             title="添加商品信息"
             center
             width="600px">
    <el-form :model="spuInfo"
             :rules="rules"
             ref="addSpuInfo"
             label-width="80px">
      <el-form-item label="商品名称"
                    prop="spuName">
        <el-input placeholder="请输入商品名称"
                  v-model="spuInfo.spuName"></el-input>
      </el-form-item>
      <el-form-item label="商品描述"
                    prop="spuDescription">
        <el-input autosize
                  type="textarea"
                  placeholder="请添加商品描述"
                  v-model="spuInfo.spuDescription"></el-input>
      </el-form-item>
      <el-form-item label="商品类别">
        <el-cascader
          clearable
          placeholder="请选择商品类别"
          v-model="spuInfo.categoryId"
          :options="categories"
          :show-all-levels="false"
          :props="props"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item label="商品品牌">
        <el-select v-model="spuInfo.brandId" clearable placeholder="请选择商品品牌">
          <el-option
            v-for="item in brands"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品重量"
                    prop="weight">
        <el-input-number placeholder="重量(g)" v-model="spuInfo.weight" :precision="2" :step="0.1" :max="10000" /><span>&emsp;(tips:最大重量不超过10Kg)</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancelSave('addSpuInfo')">取消</el-button>
      <el-button type="primary"
                 @click="saveData('addSpuInfo')">保存</el-button>
    </template>
  </el-dialog>

    <el-drawer
      v-model="drawer"
      title="图片管理"
      direction="rtl"
      :size="500"
      >
      <el-button type="primary" @click="toAddImage" size="small">添加图片</el-button>
      <el-table border :data="imageList" :header-cell-style="{textAlign:'center'}" max-height="591px">
      <el-table-column  label="图片">
        <template #default="scope" width="110px">
          <el-image style="width:100px;height:100px" :src="scope.row.imgUrl" fit="contain" >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column  width="270px" 
                      label="操作">
        <template #default="scope">
          <el-button size="small" type="primary" v-if="scope.row.defaultImg != 1" @click="setDefaultImage(scope)">设置为默认</el-button>
          <el-button size="small" type="primary" @click="updateName(scope)">修改名称</el-button>
          <el-button size="small" type="danger" @click="deleteImage(scope)">删除</el-button>
        </template>
      </el-table-column>
      </el-table>
    </el-drawer>

  <el-dialog v-model="uploadImage" title="上传图片" width="550px">
  <span>一次性最多上传5张照片，超出的会替换第五张</span>
  <el-upload 
            :action="''"
            list-type="picture-card" 
            :auto-upload="false"
            :before-upload="getPolicy"
            :on-change="change"
            :on-exceed="exceedHandle"
            :http-request="go"
            :limit="5"
            ref="uploadImageRef" >
    <el-icon><Plus /></el-icon>

    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
      </div>
    </template>
  </el-upload>

  <template #footer>
    <el-button @click="cancelUpload">取消</el-button>
    <el-button type="primary" @click="upload" >上传</el-button>
  </template>
  </el-dialog>
</template>

<script>
import {ref, getCurrentInstance, reactive} from 'vue'
import {genFileId,ElMessageBox} from 'element-plus'
import axios from 'axios'

export default {
  name: "SpuInfo",
  setup(){
    const addSpuInfo = ref()
    const uploadImageRef = ref()
    const {proxy} = getCurrentInstance();

    const SpuInfo = reactive({
      brandNama: null,
      categoryName: null,
      publishStatus: 0,
      spuDescription: null,
      spuName: null,
      weight: 0
    })
    const drawer_spu = ref(false);

    const exceedHandle = (files) =>{
      uploadImageRef.value.handleRemove(proxy.fileList[4])
      const file = files[0]
      file.uid = genFileId()
      uploadImageRef.value.handleStart(file)
    }

    const change = (file,fileList) =>{
      proxy.fileList = fileList
    }

    const toDetail = (scope) => {
      SpuInfo.value = {...scope.row}
      drawer_spu.value = true;
    }

    const toAddImage = () =>{
      proxy.uploadImage = true
      if(uploadImageRef.value){
        uploadImageRef.value.clearFiles()
      }
     
    }

    const handleRemove = (file) =>{
      uploadImageRef.value.handleRemove(file)
    }

    return {addSpuInfo,uploadImageRef,drawer_spu,SpuInfo,exceedHandle,change,toAddImage,handleRemove,toDetail}
  },
  data(){
    return {
      authority: {
        total: false,
        spuInfoAdd: false,
        spuInfoUpdate: false,
        spuInfoDelete: false
      },
      drawer:false,
      uploadImage:false,
      fileList:[],
      objectDataMap:new Map(),
      nowSpuId:-1,
      imageList:[],
      pageInfo: {
        pageNum: 1,
        pageSize: 10,
      },
      categories:[

      ],
      categoryMap:new Map(),
      brandMap:new Map(),
      brands:[

      ],
      spuInfo:{
        
      },
      disableDialog:false,
      addDisableDialog:false,
      props : {
        expandTrigger: 'hover',
        value:'id',
        label:'name'
      },
      rules: {
        spuName: [
          { required: true, message: "请输入商品名称", trigger: ['blur', 'change'] },
          { min: 1, max: 10, message: '商品名长度必须在1-10个字符之间', trigger: ['blur', 'change'] },
        ],
        spuDescription: [
          { required: true, message: "请输入商品描述", trigger: ['blur', 'change'] },
          { min: 1, max: 100, message: '商品描述不能超过100个字符', trigger: ['blur', 'change'] },
        ],
        weight: [
          { required: true, message: "请输入商品重量", trigger: ['blur', 'change'] },
        ]
      },
    }
  },
  methods:{
    initAuthority () {
      this.authority.total = this.$store.state.authority[this.$power.map.get("商品管理-Spu管理").property]
      this.authority.spuInfoAdd = this.$store.state.authority[this.$power.map.get("商品管理-Spu管理-添加").property]
      this.authority.spuInfoUpdate = this.$store.state.authority[this.$power.map.get("商品管理-Spu管理-修改").property]
      this.authority.spuInfoDelete = this.$store.state.authority[this.$power.map.get("商品管理-Spu管理-删除").property]
      Object.freeze(this.authority)
      this.$power.totalCheckAuthority(this.authority)
    },
    toSkuInfo(scope){
      let passSpuInfo = {...scope.row};
      this.$router.push({ name:'skuinfo',query:{
        categoryId:passSpuInfo.categoryId,
        brandId:passSpuInfo.brandId,
        categoryName:this.categoryMap.get(passSpuInfo.categoryId),
        brandName:this.brandMap.get(passSpuInfo.brandId),
        spuName:passSpuInfo.spuName,
        spuId:passSpuInfo.id
        }})
    },
    publish(scope){
      let url = this.$url.PmsSpuInfoControllerBaseUrl + "/changePublishStatus";
      this.$http.post(url, scope.row.id).then(res => {
        if(res.data.code == 2000){
          //状态修改成功
          this.$message({
            message: res.data.message,
            type:"success"
          })
          this.showData()
        }
      })
    },
    categoryInit(){
      let url = this.$url.PmsCategoryControllerBaseUrl + "/getAllCategory";
      this.$http.get(url).then(res => {
        this.categories = res.data.data.data;
      })
      let getThirdURL = this.$url.PmsCategoryControllerBaseUrl + "/getAllThirdCategory";
      this.$http.get(getThirdURL).then(res => {
        let list = res.data.data;
        for(let item of list){
          this.categoryMap.set(item.id,item.name)
        }
      })
    },
    brandInit() {
      let url = this.$url.PmsBrandControllerBaseUrl + "/getAllBrands";
      this.$http.get(url).then(res => {
        this.brands = res.data.data;
        for(let item of this.brands){
          this.brandMap.set(item.id,item.name)
        }
      })
    },
    showData () {
      let params = {
        pageNum: this.pageInfo.pageNum,
        pageSize: this.pageInfo.pageSize
      }
      let url = this.$url.PmsSpuInfoControllerBaseUrl + "/getPaged";
      this.$http.get(url, { params: params }).then(res => {
        this.pageInfo = res.data.data;
        for(let item of this.pageInfo.list){
          item.categoryName = this.categoryMap.get(item.categoryId);
          item.brandName = this.brandMap.get(item.brandId)
        }
      })
    },
    handleCurrentChange () {
      this.showData();
    },
    handleSizeChange () {
      this.showData();
    },
    handleChange (value) {
      if(value == null){
        this.spuInfo.categoryId = -1;
      }else{
        this.spuInfo.categoryId = value[2]
      }
    },
    del (scope) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = this.$url.PmsSpuInfoControllerBaseUrl + `/check/deleteSpu?id=${scope.row.id}`;
        this.$http.delete(url).then(res => {
          if (res.data.code == 2000) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            });
          }
          this.showData();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    add () {
      this.addDisableDialog = true;
      this.spuInfo = {};
    },
    edit(scope){
      this.disableDialog = true;
      this.spuInfo = {};
      this.spuInfo = { ...scope.row };
    },
    cancelSave(ref_name){
      if (this.disableDialog) {
        this.mes = "已取消保存"
      }
      if (this.addDisableDialog) {
        this.addSpuInfo.resetFields()
        this.mes = "已取消添加"
      }
      this.$confirm("数据尚未保存，是否取消？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.disableDialog) {
          this.$refs[ref_name].resetFields();
          this.disableDialog = false;
        }
        if (this.addDisableDialog) {
          this.$refs[ref_name].resetFields();
          this.addDisableDialog = false;
        }
        this.spuInfo = {}
        this.$message({
          type: 'info',
          message: this.mes
        });
      })
    },
    saveData (ref_name) {
      this.$refs[ref_name].validate((valid) => {
        if (valid) {
          if (this.disableDialog) {
            this.$confirm("数据即将保存，是否确认？", "提示", {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let url = this.$url.PmsSpuInfoControllerBaseUrl + "/check/update";
              this.$http.post(url, this.spuInfo).then(res => {
                if (res.data.code === 2000) {
                  this.$message({
                    type: 'success',
                    message: '保存成功!'
                  });
                  this.$refs[ref_name].resetFields();
                  this.disableDialog = false;
                  this.showData();
                  this.spuInfo = {};
                } else {
                  this.$message({
                    type: 'error',
                    message: res.data.message
                  });
                }
              })
            })
          }
          if (this.addDisableDialog) {
            this.$confirm("数据即将保存并添加，是否确认？", "提示", {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let url = this.$url.PmsSpuInfoControllerBaseUrl + "/check/insert";
              this.$http.post(url, this.spuInfo).then(res => {
                if (res.data.code === 2000) {
                  this.$message({
                    type: 'success',
                    message: '添加成功!'
                  });
                  this.$refs[ref_name].resetFields();
                  this.addDisableDialog = false;
                  this.showData();
                  this.spuInfo = {};
                  this.pageInfo.pageNum = 1;
                } else {
                  this.$message({
                    type: 'error',
                    message: res.data.message
                  });
                }
              })
            })
          }
        }
      })
      this.showData()
    },
    toImageManage(scope){
      this.nowSpuId = scope.row.id
      this.getImageList()
      this.drawer = true
    },
    getPolicy(file){
      return new Promise(((resolve,reject) => {
        this.$http.get(this.$url.OSSControllerBaseUrl + '/getPolicyForSpu',{
          params:{
            spuId:this.nowSpuId
          }
        }).then(res => {
          let objectData = {}
          objectData.OSSAccessKeyId = res.data.data.accessid;
          objectData.policy = res.data.data.policy;
          objectData.Signature = res.data.data.signature;
          objectData.dir = res.data.data.dir;
          objectData.host = res.data.data.host;
          objectData.key = res.data.data.key;
          objectData.url = objectData.host + '/' + objectData.key
          this.objectDataMap.set(file.uid,objectData)
          resolve(true)
        })
        .catch(err =>{
          console.log(err)
          reject(false)
        })
      }))
    },
    upload(){
     this.uploadImageRef.submit() 
    },
    uploadError(err){
      console.log(err)
    },
    uploadSuccess(url){
      let form = new FormData
      form.append('url',url)
      form.append('spuId',this.nowSpuId)
      this.$http.put(this.$url.PmsSpuImagesControllerBaseUrl + '/updateImageUrl',form)
        .then(res => {
          if(res.data.code === 2000){
            this.$message({
              message:res.data.message,
              type:'success'
            })
            this.getImageList()
            this.cancelUpload()
          }else{
            this.$message({
              message:res.data.message,
              type:'error'
            })
          }
        })
    },
    go(data){
      let form = new FormData()
      let uid = data.file.uid
      let object = this.objectDataMap.get(data.file.uid)
      form.append("OSSAccessKeyId",object.OSSAccessKeyId)
      form.append("policy",object.policy)
      form.append("Signature",object.Signature)
      form.append("dir",object.dir)
      form.append("key",object.key)
      form.append("host",object.host)
      form.append("file",data.file)
      axios.create().post(object.host,form).then(()=>{
        this.objectDataMap.delete(uid)
        this.uploadSuccess(object.url)
      }).catch(err=>{
        this.uploadError(err)
      })
    },
    cancelUpload(){
      this.uploadImage = false
    },
    getImageList(){
      this.$http.get(this.$url.PmsSpuImagesControllerBaseUrl + '/getImageBySpu',{params:{spuId:this.nowSpuId}})
        .then(res => {
          if(res.data.code === 2000){
            this.imageList = res.data.data
          }
        })
    },
    setDefaultImage(scope){
      this.$http.get(this.$url.PmsSpuImagesControllerBaseUrl + '/setDefault',{
        params:{
          id:scope.row.id,
          spuId:this.nowSpuId,
          now:scope.row.defaultImg
        }
      }).then(res =>{
        if(res.data.code === 2000){
          this.$message({
            message:res.data.message,
            type:'success'
          })
          this.getImageList()
        }else{
          this.$message({
            message:res.data.message,
            type:'error'
          })
        }
      })
    },
    deleteImage(scope){
      console.log(scope)
      this.$http.delete(this.$url.PmsSpuImagesControllerBaseUrl + '/deleteImage',{params:{id:scope.row.id}})
        .then(res =>{
          if(res.data.code === 2000){
            this.$message({
              message:res.data.message,
              type:'success'
            })
            this.getImageList()
          }else{
            this.$message({
              message:res.data.message,
              type:'error'
            })
          }
        })
    },
    updateName(scope){
      ElMessageBox.prompt("请输入图片名称","修改图片名称",{
        confirmButtonText: '确认修改',
        cancelButtonText: '取消'
      }).then(({value})=>{
        this.$http.get(this.$url.PmsSpuImagesControllerBaseUrl + '/updateName',{params:{id:scope.row.id,name:value}})
          .then(res =>{
            if(res.data.code === 2000){
              this.$message({
                message:res.data.message,
                type:'success'
              })
              this.getImageList()
            }else{
              this.$message({
                message:res.data.message,
                type:'error'
              })
            }
          })
      })
    },
    toAttr(scope){
      this.$router.push({path:'/main/product/spuAttr',query:{
        spuId:scope.row.id,
        categoryName:scope.row.categoryName,
        brandName:scope.row.brandName}})
    }

  },
  created() {
    this.categoryInit(),
    this.brandInit(),
    this.showData(),
    this.initAuthority()
  }
}
</script>

<style scoped>

</style>